/*
' Copyright (c) 2012-2013 Kyriakos Lesgidis
'  All rights reserved.
' 
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
' 
*/

using System;
using DotNetNuke.Services.Exceptions;
using net.diadrasis.CameraSlideshow.Components;
using System.Web.UI.WebControls;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Common;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities;
using System.Collections.Generic;
using System.Data;

namespace net.diadrasis.CameraSlideshow
{

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The EditCameraSlideshow class is used to manage content
    /// 
    /// Typically your edit control would be used to create new content, or edit existing content within your module.
    /// The ControlKey for this control is "Edit", and is defined in the manifest (.dnn) file.
    /// 
    /// Because the control inherits from CameraSlideshowModuleBase you have access to any custom properties
    /// defined there, as well as properties from DNN such as PortalId, ModuleId, TabId, UserId and many more.
    /// 
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class Edit : CameraSlideshowModuleBase
    {
        private int rowindex = -1;        
        public List<string> folderPaths;
        public DataTable images = new DataTable();

        #region Event Handlers

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// -----------------------------------------------------------------------------
        
        private void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                //Implement your edit logic for your module
                if (!IsPostBack)
                {                               
                    images.Load(cMediaObjectController.getMediaByObject(ModuleId));          

                    System.Collections.Generic.IEnumerable<IFolderInfo> folders = FolderManager.Instance.GetFolders(PortalId);
                    folderPaths = new List<string>();                    
                    
                    int startPos = Globals.ApplicationMapPath.Length + "\\Portals\\".Length + PortalId.ToString().Length;
                    foreach (IFolderInfo f in folders)
                    {
                        string path = f.PhysicalPath.Substring(startPos, f.PhysicalPath.Length - startPos);
                        DropDownList1.Items.Add(new ListItem(path, f.FolderID.ToString()));
                    }

                    DropDownList1.DataBind();                    
                }
               
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }     

        #endregion

        #region Custom Functions

        public string getImageUrl(string fID)
        {
            if (fID != "")
            {
                FileController fileCnt = new FileController();
                FileInfo objFile = fileCnt.GetFileById(Convert.ToInt32(fID.Substring(7)), PortalId);
                try
                {
                    return Globals.GetPortalSettings().HomeDirectory + objFile.Folder + objFile.FileName;
                }
                catch (Exception ex)
                {
                    return "";
                    //file doesn't exist
                }
            }else
                return "";
        }

        #endregion               
        
        protected void LinkButton1_Click(object sender, EventArgs e)
        {            
            ImportImages( Convert.ToInt32(DropDownList1.SelectedValue) );

            Response.Redirect(Request.RawUrl);
        }

        protected void LinkButton3_Click(object sender, EventArgs e)
        {
            // Create the thumbnails            
            Synchronize();
        }
        

        public bool ThumbnailCallback()
        {
            return false;
        }

        public void GetThumbnails()
        {
            string[] filePaths = System.IO.Directory.GetFiles(@DropDownList1.SelectedValue);

            System.Drawing.Image.GetThumbnailImageAbort callback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

            foreach (string filePath in filePaths)
            {
                if (!filePath.Contains("thumb"))
                {
                    string fileName = filePath.Substring(0, filePath.LastIndexOf("."));
                    string extention = filePath.Substring(filePath.LastIndexOf("."), filePath.Length - filePath.LastIndexOf("."));
                    int thumbHeight = 40;

                    System.Drawing.Image source = System.Drawing.Image.FromFile(filePath);
                    System.Drawing.Image thumb = source.GetThumbnailImage(source.Width * thumbHeight / source.Height, thumbHeight, callback, IntPtr.Zero);

                    thumb.Save(fileName + "-thumb" + extention);
                }
            }            
        }

        private void Synchronize()
        {
            cMediaObjectController.deleteAllMedia(ModuleId);
            ImportImages(Convert.ToInt32(DropDownList1.SelectedValue));

            Response.Redirect(Request.RawUrl);
        }

        private void ImportImages(int folderID)
        {
            //Get all files by folder id
            System.Collections.Generic.IEnumerable<IFileInfo> files = FolderManager.Instance.GetFiles( FolderManager.Instance.GetFolder(folderID) );

            foreach (FileInfo f in files)
            {
                //if the file is an image                
                if (Globals.glbImageFileTypes.Contains(f.Extension.ToLower()))
                {
                    //if file is not thumb
                    if (!f.FileName.Contains("thumb"))
                    {
                        cMediaObject m = new cMediaObject();
                        m.moduleId = ModuleId;
                        m.mediaObjectUrl = "FileID=" + f.FileId;
                        m.mediaObjectCaption = "";
                        cMediaObjectController.addMedia(m);

                        CreateThumbnail(getImageUrl("FileID=" + f.FileId));
                    }
                }
            }
        }

        public void CreateThumbnail(string filePath)
        {
            if (filePath != "")
            {
                System.Drawing.Image.GetThumbnailImageAbort callback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

                int thumbHeight = 50;
                System.Drawing.Image source = System.Drawing.Image.FromFile(@Server.MapPath(filePath));
                System.Drawing.Image thumb = source.GetThumbnailImage(source.Width * thumbHeight / source.Height, thumbHeight, callback, IntPtr.Zero);

                thumb.Save(@Server.MapPath(getThumbPath(filePath)));
            }
        }

        public string getThumbPath(string filePath)
        {
            string fileName = filePath.Substring(0, filePath.LastIndexOf("."));
            string extention = filePath.Substring(filePath.LastIndexOf("."), filePath.Length - filePath.LastIndexOf("."));

            return fileName + "-thumb" + extention;
        }       

        protected void LinkButton2_Click(object sender, EventArgs e)
        {
            FolderManager.Instance.Synchronize(PortalId, "", true, true);
            Response.Redirect(Request.RawUrl);      
        }        

    }

}